from flask import Blueprint,request,jsonify
from application import app
import json,re
from common.libs.UploadService import UploadService
from common.libs.UrlManager import UrlManager
from common.models.Image import Image

route_upload=route_index =Blueprint('upload_page',__name__)

@route_upload.route("/ueditor",methods=["GET","POST"])
def ueditor():
    req = request.values
    action = req['action'] if 'action' in req else ''
    if action == "config":
        # 定义一个json对象
        config_data = {}
        root_path = app.root_path
        config_path = "{0}/web/static/plugins/ueditor/upload_config.json".format(root_path)
        # 读文件 :fp句柄
        with open(config_path,encoding="utf-8") as fp:
            try:
                # .*任何字符串都可以
                config_data = json.loads(re.sub(r'\/\*.*\*/', "", fp.read()))
            except:
                config_data = {}
        return jsonify(config_data)

    # 本地上传
    if action =="uploadimage":
        return uploadImage()

    # 在线管理
    if action =="listimage":
        return listImage()
    return "upload"

@route_upload.route("/pic",methods=["GET","POST"])
def uploadPic():
    file_target = request.files
    # pic 是set.html中的对应name的值
    upfile = file_target['pic'] if 'pic' in file_target else None

    # 调取父页面
    callback__target ='window.parent.upload'
    if upfile is None:
        # 1.
        # script是一个js事件  需要返回的是事件：首先 将callback__target的error事件的错误信息放进error中error('{1}')---再用format将错误参数传进去{0}里面----最后显示就是callback__target的错误信息
        return "<script type ='text/javascript'>{0}.error('{1}')</script>"\
            .format(callback__target,"上传失败")

    # 2.上传图片
    ret = UploadService.uploadByFile(upfile)
    if ret['code'] != 200:
        return "<script type ='text/javascript'>{0}.error('{1}')</script>" \
            .format(callback__target, "上传失败"+ret['msg'])

    #3.上传成功调用success方法：
    return "<script type ='text/javascript'>{0}.success('{1}')</script>" \
        .format(callback__target, ret['data']['file_key'])

# 上传图片方法
def uploadImage():
    resp ={'state':'SUCCESS','url':'','title':'','original':''}
    # 取出文件类型
    file_target =request.files
    upfile =file_target['upfile'] if 'upfile' in file_target else None
    if upfile is None:
        resp['state']="上传失败"
        print("=============================")
        app.logger.info(file_target)
        return jsonify(resp)
    # 如果有的图片话就真的进行上传动作
    # 封装一个统一的上传方法(减轻业务的复杂度)
    ret = UploadService.uploadByFile(upfile)
    #  调用成功后会有返回值,判断：如果返回来的不是200，则错误
    if ret['code'] !=200:
        resp['state'] = "上传失败"+ret['msg']
        return jsonify(resp)

    # 成功后resp中的地址返回，将图片嵌入网页中
    resp['url'] =UrlManager.buildImageUrl(ret['data']['file_key'])
    return jsonify(resp)

# 图片展示方法：返回上传的所有图片：数据库中取得这些之前存进来的图片
# 结合uploadImage()和listImage()两个方法，先上传图片到数据库，再从数据库中取出来
def listImage():
    resp ={'state':'SUCCESS','list':[],'start':0,'total':0}

    # 获取所有表单参数
    req =request.values

    start =int(req['start']) if 'start' in req else 0
    page_size =int(req['size']) if 'size' in req else 20

    # 在线图片分页显示 通过id
    # 先倒序取0-20个，再根据剩下的图片数量倒序取20个，不满20个就去剩下的个数
    query = Image.query
    if start > 0:
        query = query.filter(Image.id < start)

    # 图片从0开始到size通过id查 有多少张  偏移量id小于8，倒序排取20个
    list =query.order_by(Image.id.desc()).limit(page_size).all()
    images=[]
    if list:
        for item in list:
            # 取图片地址
            images.append({'url':UrlManager.buildImageUrl(item.file_key)})
            start=item.id
    # 所有图片地址存到list中
    resp['list']= images
    resp['start']= start
    # 图片长度
    resp['total'] =len(images)

    return jsonify(resp)